<?php
	global $CFG;
	
	$output = "<HTML><BODY>";
	
	if($_COOKIE['ajaxMapUser'] != NULL)
		$user = $_COOKIE['ajaxMapUser'];
	
	if($_COOKIE['ajaxMapPass'] != NULL)
		$pass = $_COOKIE['ajaxMapPass'];
		
	if($_COOKIE['ajaxMapFeed'] == "My friends")
		$feed = "friends_timeline.xml";			
	else
		$feed = "public_timeline.xml";	
	

	// Get the XML data from the Twitter Web Service
	$gettwit = getTwitterFeed($user, $pass, $feed);
	//echo $user . ", " . $pass . ", " . $feed . "<br />" . $gettwit;
	
	// Parse the XML data
	$xml = new XMLReader();
	$xml->XML($gettwit);

	$data = array();
	$ctr = -2;
	$thistype = 0;

	while ($xml->read())
	{
		while($xml->depth<=1    && $xml->nodeType==1)
		{
	  		$xml->read();
	  		$ctr++;
		}
		if ($xml->nodeType==1 && $xml->depth==2)
		{
			$data[$ctr]=array();
			while($xml->depth<2)
			    $xml->read();
			while($xml->depth>=2)
			{
			  	if($xml->nodeType==1)
			    {
			    	// bit of a hack to make sure an array entry is made, even if a node is empty			    
			   		if($thistype==1)
			    		$data[$ctr][] = "####";
			    		
			    	$thistype = 1;
			    }
			    
			    elseif ($xml->nodeType==3)
			    {
			    	$data[$ctr][] = $xml->value;
			    	$thistype = 3;
			    }
			    
			    $xml->read();
			}
		}	    
	}
	
	// build the output correctly, so the block can understand it	
	$i = 0;
	
	foreach ($data as $twit)
	{
		if($i < 10)
		{
			// Get the user's location
			$location = $twit[13];
			// reset the search term, so users with location "####" don't just re-use the last one
			$term = "";
			// Reset the "muser" object
			$muser = NULL;
			
			// Use the actual location if available
			if($location != '####')
			{			
			    	$term = "/search?maxRows=1&q=".urlencode($location);
			   	    $output .= "Search term (no country): " . $term . "<br/>";
			}  	
		   			   				
			// Get the coordinates
		   	$response = getURLContent("http://ws5.geonames.org", $term);		   	
		   	
		   	//echo "Search term (no country): " . $term . "<br/>" . $response;
		   	
		   	// Add the coordinates to the "muser" object
		   	if($xml = simplexml_load_string($response))
		   	{		
				if (isset($xml->geoname->lat))
				{
					$muser->lat = strip_tags($xml->geoname->lat->asXML());
		  			$muser->lng = strip_tags($xml->geoname->lng->asXML());
		  			$muser->online = "true";
            	}
				else
				{
					// No coords returned, move the user to the default location...
					$muser->lat = 30.9;
					$muser->lng = ($i/-10)-30.4;
					$muser->online = "false";
				}
		   	}
		   		
			// Build the rest of the "muser" object
			$muser->fullname = $twit[11];
			if($twit[13] != '####')
				$muser->location = $twit[13];
			else
				$muser->location = "no location given";
            $muser->lastname = "";
            $muser->firstname = "";
            $output .= "User object: " . print_r($muser, "TRUE") . "<p/>";
            $users[$i] = $muser;            
            
            $i++;
            
		}
		
	}
	
	// return the results
	header("Content-type: text/plain");
	echo phpToJSON($users, 'online');
	
	function getTwitterFeed($username, $password, $xmlfeed)
	{
	   $out  = "GET /statuses/" . $xmlfeed . " HTTP/1.1\r\n";
	   $out .= "Host: twitter.com\r\n";
	   $out .= "Connection: Close\r\n";
	   $out .= "Authorization: Basic ".base64_encode($username . ":" . $password)."\r\n";
	   $out .= "\r\n";
	   
	   if (!$conex = fsockopen("twitter.com", 80, $errno, $errstr, 30))
	       return 0;
	   fwrite($conex, $out);
	   $data = '';
	   while (!feof($conex))
	   {
	       $data .= fgets($conex, 512);
	   }
	   fclose($conex);
	   
	   $result_arr = explode("Connection: close\r\n\r\n", $data);
	   $data = $result_arr[1];
	   
	   return $data;
	}
	
	function phpToJSON($objects,$name,$callback=''){
		$str = '';
		if ($callback != ''){
			$str .= $callback.'(';
		}
		if ($objects){
			$str .= '{"'.$name.'":[';
			$okeys = array_keys($objects);
			for ($i=0; $i<sizeof($okeys); $i++ ){
				$myobj = $objects[$okeys[$i]];
				$attr = get_object_vars($myobj);
				$str .= '{';
				$keys = array_keys($attr);
				for($j=0;$j<sizeof($keys);$j++){
					$str .= '"'. $keys[$j] .'":"'. $attr[$keys[$j]] .'"';
					if ($j != (sizeof($keys)-1)){
					$str .= ',';
					}
				}
				$str .= '}';
				if ($i != (sizeof($objects)-1)){
				$str .= ',';
				}
			}
			$str .= ']}';
		}
		if ($callback != ''){
			$str .= ');';
		}
		return $str;
	}
	
	function isUTF8($string)	{    	return (utf8_encode(utf8_decode($string)) == $string);	}
	
	/**
	 * Gets the content of a url request
	 * @uses $CFG
	 * @return String body of the returned request
	 */
	function getURLContent($domain,$path){
		
		global $CFG;
	
		if($CFG->proxyhost != "" && $CFG->proxyport != 0){
	    	$address = $CFG->proxyhost;
	    	$port = $CFG->proxyport;
		} else {
			$address = str_replace("http://","",$domain);
	    	$port = 80;
		}
	    $message = "GET $domain$path HTTP/1.0\r\n";
	    $message .= "Host: $domain\r\n";
	    $message .= "Connection: Close\r\n";
	    $message .= "\r\n";
	    
	    /* Attempt to connect to the proxy server to retrieve the remote page */
	    if(!$socket = fsockopen($address, $port, $errno, $errstring, 20)){
	        die("Couldn't connect to host $address: $errno: $errstring\n");
	    }
	    
	    fwrite($socket, $message);
	    $content = "";
	    while (!feof($socket)){
	            $content .= fgets($socket, 1024);
	    }
	    
	    fclose($socket);
	    $retStr = extractBody($content);
	    return $retStr;
	}
	
	/**
	 * removes the headers from a url response
	 * @return String body of the returned request
	 */
	function extractBody($response){
		
		$crlf = "\r\n";
		// split header and body
	    $pos = strpos($response, $crlf . $crlf);
	    if($pos === false){
	   	    return($response);
	    }
	
	    $header = substr($response, 0, $pos);
	    $body = substr($response, $pos + 2 * strlen($crlf));
	    // parse headers
	    $headers = array();
	    $lines = explode($crlf, $header);
	   
	    foreach($lines as $line){
	   	    if(($pos = strpos($line, ':')) !== false){
	   		    $headers[strtolower(trim(substr($line, 0, $pos)))] = trim(substr($line, $pos+1));
	   	    }
	    }
	
	   	return $body;
		
	}
	

?>